#import "NSString+X.h"


@implementation NSString (X)


/**
 * 获取16进制数值的字符串输出
 * @param        data，16进制数据
 * @result       16进制数值对应的字符串输出，如：0xABCD 则 输出 @“ABCD”
 */
+ (instancetype)stringWithHex:(NSData *)data {
    char szHex[32] = {0};
    char szBuf[32] = {0};
    NSUInteger uLenght = data.length;
    [data getBytes:szBuf length:uLenght];
    for (int i = 0; i < uLenght; i++) {
        int nHex = szBuf[i];
        int nHigh = (nHex >> 4) & 0xf;
        int nLow = nHex & 0xf;
        nHigh += nHigh > 9 ? 55 : 48;       // 之所以 是 55 而不是 65 是因为对应的数值是从 10 开始的 10 + 55 刚好就是 A，如此类推
        nLow += nLow > 9 ? 55 : 48;
        szHex[i * 2] = nHigh;
        szHex[i * 2 + 1] = nLow;
    }
    
    return [NSString stringWithFormat:@"%s", szHex];
}


/**
 * 判断字符串当中是否有指定的字符
 * @param        special，特殊字符组成的字符串
 * @result       YES，有指定的特殊字符，NO，无指定的特殊字符
 */
- (BOOL)hasSpecialCharacters:(NSString *)special {
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:special] invertedSet];
    NSString *strFilter = [special stringByTrimmingCharactersInSet:cs];
    if ( strFilter.length != special.length) {
        return YES;
    }
    
    return NO;
}


/**
 * 判断字符串当中是否有指定的字符
 * @param        type，特殊字符组成的字符串
 * @result
 */
- (BOOL)hasSpecialCharacterTypes:(CharacterTypeEnum)type {
    BOOL (^stringNotHaveCharacterInSet)(NSString *, NSCharacterSet *) = ^(NSString *string, NSCharacterSet *cs) {
        NSString *strFilter = [string stringByTrimmingCharactersInSet:cs];
        if ( strFilter.length != string.length) {
            return NO;
        }
        return YES;
    };
    
    BOOL bRet = YES;
    
    if (type & CharacterTypeWhitespace) {
        // 空格
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet whitespaceCharacterSet]);
    }
    
    if (bRet && type & CharacterTypeLowercaseAlpha) {
        // 小写字母
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet lowercaseLetterCharacterSet]);
    }
    
    if (bRet && type & CharacterTypeUppercaseAlpha) {
        // 大写字母
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet capitalizedLetterCharacterSet]);
    }
    
    if (bRet && type & CharacterTypeDigit) {
        // 数字
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet decimalDigitCharacterSet]);
    }
    
    if (bRet && type & CharacterTypeSymbol) {
        // 符号
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet symbolCharacterSet]);
    }
    
    if (bRet && type & CharacterTypePunctuation) {
        // 标点
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet punctuationCharacterSet]);
    }
    
    if (bRet && type & CharacterTypeNewLine) {
        // 换行
        bRet &= stringNotHaveCharacterInSet(self, [NSCharacterSet newlineCharacterSet]);
    }
    
    return !bRet;
}


@end

